import http from './http'

declare global {
  interface Window {
    wx: any
    WeixinJSBridge: any
  }
}

export function isWeixin(): boolean {
  const ua = window.navigator.userAgent.toLowerCase()
  return !!ua.match(/micromessenger/i)
}

export async function initWXConfig(options?: {
  title?: string
  desc?: string
  link?: string
  imgUrl?: string
}) {
  if (!isWeixin())
    return

  const { data } = await http.get(
    `/api/calc/jssdk?url=${encodeURIComponent(window.location.href)}`,
  )
  const { wx } = window

  wx?.config({
    debug: false,
    appId: data.appId,
    timestamp: data._wxTimestamp,
    nonceStr: data._wxNoncestr,
    signature: data._wxSignature,
    jsApiList: [
      'onMenuShareAppMessage',
      'onMenuShareTimeline',
      'updateAppMessageShareData',
      'updateTimelineShareData',
    ],
  })

  wx?.ready(() => {
    const shareData = {
      title: '餐饮必备计算神器',
      desc: '盈利亏损一目了然',
      link: window.location.origin,
      imgUrl: 'https://cm.hawnlink.cn/share.jpg?v=1.0.0',
      ...options,
    }

    wx.onMenuShareAppMessage(shareData)
    wx.onMenuShareTimeline(shareData)
    wx.updateAppMessageShareData(shareData)
    wx.updateTimelineShareData(shareData)

    window.WeixinJSBridge.call('showOptionMenu')
  })
  wx?.error((error: any) => {
    console.error('wx.error is', error)
    // config信息验证失败会执行 error 函数，如签名过期导致验证失败，具体错误信息可以打开 config 的debug模式查看，也可以在返回的 res 参数中查看，对于 SPA 可以在这里更新签名。
  })
}
